<template>
  <view>
    <mg-popup v-model="showGgCom" :z-index="3000">
      <view v-if="loading" class="bs15 bf ggjz">
        <view class="dhtmd">
          <view class="bf6 jzi1"></view>
          <view class="bf6 jzi2 p3"></view>
          <view class="bf6 jzi2 p3"></view>
        </view>
      </view>
      <view v-else class="ggc bs15 bf posi-r" style="padding-bottom: 270px">
        <view @click="showGgCom = false" class="ggx posi-a r0">
          <text class="iconfont iconyx f56"></text>
        </view>
        <view class="ggtop f-row">
          <view class="ggh mr30 f-g-0 bs20">
            <mg-img :src="goodsInfo.icon"></mg-img>
          </view>
          <view>
            <view class="f36 wei">{{ goodsInfo.name }}</view>

            <view class="mt15 f24 c7">套餐商品描述</view>
            <view class="mt15 f24 c9 t-o-e3 w100">{{ goodsInfo.body }}</view>
          </view>
        </view>

        <view style="overflow-y: auto; height: 472px">
          <view
            style="margin: 0px 20px; margin-top: 10px; font-weight: 700"
            class="c6"
            >固定搭配</view
          >
          <scroll-view
            scroll-x="true"
            class="ggb p23"
            style="height: 300px; width: 100%"
          >
            <view class="" style="display: flex; flex-wrap: nowrap">
              <block v-if="goodsInfo.comboGoodsArr">
                <view class="f-raw" style="display: flex">
                  <view
                    v-for="(_comboGood, pi) in goodsInfo.comboGoodsArr"
                    :key="pi"
                    class="specv t-o-e f26"
                    :style="{
                      background: _comboGood.a ? tColor : '',
                      color: _comboGood.a ? '#fff' : '',
                      width: '130px' /* 设置固定宽度 */,
                      height: '250px' /* 设置固定高度 */,
                      display: 'flex',
                      flexDirection: 'column',
                      alignItems: 'center',
                      justifyContent: 'center',
                      margin: '0 10px' /* 设置元素之间的间距 */,
                    }"
                  >
                    <view>
                      <mg-img
                        :src="_comboGood.icon"
                        style="width: 100px; height: 100px"
                      ></mg-img>
                      <!-- 设置图片大小 -->
                    </view>
                    <view>{{ _comboGood.name }}</view>
                    <view
                      >{{ _comboGood.num }}份（￥{{
                        _comboGood.SalesPrice
                          ? _comboGood.SalesPrice
                          : _comboGood.price
                      }}）</view
                    >
                    <view style="position: relative; display: inline-block">
                      <button
                        @click="selectSpecs(_comboGood)"
                        class="jrgwctc"
                        style=""
                      >
                        选规格
                      </button>
                    </view>
                  </view>
                </view>
              </block>
            </view>
          </scroll-view>

          <!-- 可选搭配 -->
          <view
            style=""
            v-for="(pv, pi1) in goodsInfo.kecomboGoodsArr"
            :key="pi1"
          >
            <view
              style="margin: 0px 20px; margin-top: 10px; font-weight: 700"
              class="c6"
              >{{ pv.fzname }} 必选({{ pv.fznum }})
            </view>
            <scroll-view
              scroll-x="true"
              class="ggb p23"
              style="height: 300px; width: 100%"
            >
              <view class="" style="display: flex; flex-wrap: nowrap">
                <view class="f-raw" style="display: flex">
                  <view
                    v-for="(pvgoods, pigoods) in pv.goods"
                    :key="pigoods"
                    class="specv t-o-e f26"
                    :style="{
                      background: pvgoods.a ? tColor : '',
                      color: pvgoods.a ? '#fff' : '',
                      width: '130px' /* 设置固定宽度 */,
                      height: '250px' /* 设置固定高度 */,
                      display: 'flex',
                      flexDirection: 'column',
                      alignItems: 'center',
                      justifyContent: 'center',
                      margin: '0 10px' /* 设置元素之间的间距 */,
                    }"
                  >
                    <view>
                      <mg-img
                        :src="pvgoods.icon"
                        style="width: 100px; height: 100px"
                      ></mg-img>
                      <!-- 设置图片大小 -->
                    </view>
                    <view>{{ pvgoods.name }}</view>
                    <view>￥{{ pvgoods.addprice }}</view>
                    <!-- <view>
											<button @click="jrgwctcaddprice(pi1, pigoods, pvgoods)" class="jrgwctc"
												style="">
												+
											</button>
										</view> -->
                    <view style="position: relative; display: inline-block">
                      <button
                        @click="selectSpecs(pvgoods, true)"
                        class="jrgwctc"
                        style=""
                      >
                        选规格
                      </button>
                    </view>
                  </view>
                </view>
              </view>
            </scroll-view>
          </view>
        </view>

        <view
          v-if="goodsInfo.id"
          style="
            position: fixed;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 300px;
          "
        >
          <view class="posi-r ggf bf f-col f-x-ad">
            <view style="height: 190px; overflow-y: auto">
              <!-- 固定搭配的套餐 -->
              <view
                class="f-x-bt"
                v-for="(pvss, pisss) in goodsInfoArrGd"
                :key="pisss"
              >
                <view class="f-g-1">
                  <view class="f-raw" :style="{ color: tColor }">
                    {{ pvss.name }}:
                    <text v-if="pvss.jldata" class="f34 wei mr20"
                      >{{ pvss.jldata }}
                    </text>
                    <text v-if="pvss.attribute">{{ pvss.attribute }}</text>
                  </view>
                  <view class="f22 c9 t-o-e3">
                    {{ sl + pvss.price }} {{ pvss.jlmoney ? "+" : "" }}
                    {{ sl + pvss.jlmoney ? pvss.jlmoney : 0 }}
                  </view>
                </view>
              </view>

              <!-- 可选搭配的套餐 -->
              <view
                class="f-x-bt"
                v-for="(pv1, pi1) in goodsInfoArr"
                :key="pi1"
              >
                <view class="f-g-1" v-if="pv1.ggnum > 0">
                  <view class="f-raw" :style="{ color: tColor }">
                    {{ pv1.name }}:
                    <text v-if="pv1.jldata" class="f34 wei mr20"
                      >{{ pv1.jldata }}
                      <!-- <text class="f24 nowei c9 ml10">1</text> -->
                    </text>
                    <text v-if="pv1.attribute" class="">{{
                      pv1.attribute
                    }}</text>
                  </view>
                  <view class="f22 c9 t-o-e3">
                    {{ sl + pv1.price }}
                  </view>
                </view>
                <view class="f-g-0 f-bt ml30" v-if="pv1.ggnum > 0">
                  <view class="reducecon active f-y-c">
                    <view @click.stop="decSpec(pv1)" class="cartc f-c">
                      <text
                        class="iconfont iconjs f54"
                        :style="{ color: tColor }"
                      ></text>
                    </view>
                    <text class="f34 ma c0">{{ pv1.ggnum }}</text>
                  </view>
                  <view @click.stop="addSpec(pv1, pi1)" class="cartc f-c">
                    <text
                      class="iconfont iconzj f54"
                      :style="{ color: tColor }"
                    ></text>
                    <!-- <button class="cartadd" :style="{background:tColor}"></button> -->
                  </view>
                </view>
              </view>
            </view>
            <view class="f34 wei mr20" style="color: rgb(219, 168, 111)">
              该套餐总价：￥{{ pvprice }}
            </view>
            <button
              @click="addCart"
              :style="{ background: tColor }"
              class="w100 cf ggbtn mt10 f34 f-c"
            >
              加入购物车
            </button>
          </view>
        </view>
      </view>
    </mg-popup>

    <speccomss
      @addeee="handleAddAaa"
      :co="goodsInfoDp"
      :storeid="storeid"
      :systemGood="system"
      v-model="showGg"
    >
    </speccomss>
  </view>
</template>

<script>
import { mapState } from "vuex";
import mgPopup from "@/components/common/popup.vue";
import bkB from "@/components/common/block-b.vue";
import speccomss from "@/components/goods/speccomss.vue";
import utils from "@/common/utils.js";
import util from "@/common/we7/util";
export default {
  name: "popup",
  components: {
    mgPopup,
    bkB,
    speccomss,
  },
  props: {
    co: {
      type: Object,
      default: function () {
        return {};
      },
    },
    cname: {
      type: String,
      default: "",
    },
    value: {
      type: Boolean,
      default: false,
    },
    width: {
      type: String,
      default: "70%",
    },
    zindex: {
      type: Number,
      default: 999,
    },
    storeid: {
      type: String,
      default: "",
    },
    systemGood: {
      type: Object,
      default: function () {
        return {};
      },
    },
  },
  data() {
    return {
      outin: "1",
      goodsInfoDp: {},
      showGg: false,
      loading: true,
      goodsInfo: {},
      goodsInfoArr: [], // 可选搭配的数据

      goodsInfoArrGd: [], // 固定搭配的数组
      comboCounts: {},
      /* 当前规格弹窗是否是选择选配弹窗 */
      isSelectSpecs: false,
    };
  },
  methods: {
    addSpec(_data, _specIndex) {
      const fzObj = this.goodsInfo.kecomboGoodsArr.find(
        (item) => item.goodGroupId === _data.goodGroupId
      );

      console.log("_data, _specIndex", { _data, _specIndex, fzObj });

      /* 当前套餐下的已选择数量 */
      let selectedCount = 0;
      this.goodsInfoArr.forEach((_g) => {
        selectedCount += _g.ggnum;
      });

      if (selectedCount >= fzObj.fznum) {
        alert(`不能再加了`);
        return;
      }

      // const _index = this.goodsInfoArr.findIndex((item) => item.id === _data.id);
      this.goodsInfoArr.splice(_specIndex, 1, {
        ..._data,
        ggnum: _data.ggnum + 1,
      });
    },
    async handleAddAaa(e) {
      if (e.g.SalesStock && e.g.SalesStock <= 0)
        return this.util.message("商品已售罄", 3);
      if (e.g.stock <= 0) return this.util.message("商品已售罄", 3);

      if (!this.isSelectSpecs) {
        const itemIndex = this.goodsInfoArrGd.findIndex(
        	(item) => item.id === e.g.id
        );
        if (itemIndex !== -1) {
        	// 如果找到了对应的元素，更新它的price属性
        	this.goodsInfoArrGd.splice(itemIndex, 1, {
        		...e.g,
        	})

        } else {

        	this.goodsInfoArrGd.push(e.g);
        }
        // this.goodsInfoArrGd.push(e.g);
      } else {
        // const itemIndex = this.goodsInfoArr.findIndex(
        // 	(item) => item.id === e.g.id
        // );
        // if (itemIndex !== -1) {
        // 	// 如果找到了对应的元素，更新它的price属性
        // 	this.goodsInfoArr.splice(itemIndex, 1, {
        // 		...e.g,
        // 	})

        // } else {

        // 	this.goodsInfoArr.push(e.g);
        // }
        this.goodsInfoArr.push(e.g);
      }
    },
    decSpec(_data) {
      const _index = this.goodsInfoArr.findIndex(
        (item) => item.id === _data.id
      );

      const _num = _data.ggnum - 1;

      /* 如果是0，则删除 */
      if (_num <= 0) {
        this.goodsInfoArr.splice(_index, 1);
        return;
      }
      this.goodsInfoArr.splice(_index, 1, {
        ..._data,
        ggnum: _data.ggnum - 1,
      });
    },
    // 选择规格
    selectSpecs(pv, isOptional = false) {
      /* 如果是选配套餐 */
      if (isOptional) {
        const fzObj = this.goodsInfo.kecomboGoodsArr.find(
          (item) => item.goodGroupId === pv.goodGroupId
        );

        /* 当前套餐下的已选择数量 */
        let selectedCount = 0;
        this.goodsInfoArr.forEach((_g) => {
          if (_g.goodGroupId === fzObj.goodGroupId) {
            selectedCount += _g.ggnum;
          }
        });

        if (selectedCount >= fzObj.fznum) {
          alert(`不能再加了`);
          return;
        }

        pv.price = pv.addprice;
        this.isSelectSpecs = true;
      } else {
        this.isSelectSpecs = false;
      }
      // 选择规格，弹窗出可以选择规格的东西，加料的东西
      this.showGg = true;
      pv.isSpecs = 1;
      pv.isMaterial = 1;
      pv.isAttr = 1;
      // 再请求最新的商品信息数据
      console.log("pv", pv);

      //   this.goodsInfoDp = pv;

      Object.keys(pv)?.forEach((k) => {
        this.$set(this.goodsInfoDp, k, pv[k]);
      });
    },

    // 加入购物车
    addCart: utils.throttle(function (e) {
		
		console.log('this.goodsInfoArr',this.goodsInfoArr)
		console.log('this.goodsInfoArrGd',this.goodsInfoArrGd)
		
		
      if (this.goodsInfoArr.length <= 0) {
        alert("请选择可选搭配");
        return;
      }
	  
	  
      let hasError = false;
      var kecomboGoodsArr = this.goodsInfo.kecomboGoodsArr;

      kecomboGoodsArr.forEach((fzObj) => {
        const { goods = [], fznum } = fzObj || {};

        // 获取当前套餐下的所有必选项
        const requiredItems = goods.map((_r) => _r.id);
        let selectedCount = 0;
        this.goodsInfoArr.forEach((_v) => {
          if (requiredItems.includes(_v.id)) {
            selectedCount += _v.ggnum;
          }
        });
        if (selectedCount !== fznum) {
          hasError = true;
          // alert(`请选择可选搭配`);

          return;
        }
      });

      if (hasError) {
        alert("请选择可选搭配");
        return;
      }

      let specInfo = Object.assign({}, this.xzSpecInfo),
        jlInfo = {
          jlmoney: this.xzJlInfo.money,
          material: this.xzJlInfo.arr.map((v) => ({
            materialId: v.id,
            num: 1,
          })),
          jldata: "", //本地用来显示的
          jlids: "", //本地用来判断的
        },
        sxInfo = {
          attribute: "",
        };
      specInfo.groupId = specInfo.id || "";
      //specInfo有id属性
      delete specInfo.id;
      //处理属性
      sxInfo.attribute = this.xzSxInfo.arr.map((v) => v.name).toString();
      //处理加料
      jlInfo.jldata = this.xzJlInfo.arr.map((v) => v.materialName).toString();
      jlInfo.jlids = this.xzJlInfo.arr.map((v) => v.id).toString();
      //判断购物车是否存在此商品
      let i;
      if (
        this.co.isSpecs != 1 &&
        this.co.isMaterial != 1 &&
        this.co.isAttr != 1
      ) {
        i = this.carList.find((v) => v.goodsId == this.co.id);
      } else {
        i = this.carList.find(
          (v) =>
            v.goodsId == this.co.id &&
            v.groupId == specInfo.groupId &&
            v.materialIds == jlInfo.jlids &&
            v.attribute == sxInfo.attribute
        );
      }
      if (i) {
        // 限购判断
        if (
          this.co.maxNum > 0 &&
          Number(i.num) + Number(this.goodsInfo.ggnum) > this.co.maxNum
        ) {
          return this.util.message(`此商品限购${this.co.maxNum}份`, 3);
        }
      } else {
        // 起售判断
        if (this.co.minNum > 1 && this.co.minNum > this.goodsInfo.ggnum) {
          return this.util.message(`此商品${this.co.minNum}份起购`, 3);
        }
        // 限购判断 购物车没有，想第一次添加
        if (this.co.maxNum > 0 && this.goodsInfo.ggnum > this.co.maxNum) {
          return this.util.message(`此商品限购${this.co.maxNum}份`, 3);
        }
      }
      let goods = Object.assign(
        {
          ggnum: this.goodsInfo.ggnum,
          ggdptcgd: this.goodsInfoArrGd,
          ggdptc: this.goodsInfoArr,
          ggdptcprice: this.pvprice,
        },
        this.co,
        specInfo,
        sxInfo,
        jlInfo
      );
      //父级方法
      this.$emit("add", {
        g: goods,
        addwz: 1,
      });
      this.showGgCom = false;
      // console.log('购物车项', i)
      // console.log(e, specInfo, jlInfo, goods)
    }, 300),
  },
  computed: {
    ...mapState({
      carList: (state) => state.scarList.data || [],
    }),
    pvprice() {
      let allPrice = 0;

      this.goodsInfoArr.forEach((_g) => {
        allPrice += _g.ggnum * ((_g.price ?? 0) * 1 + (_g.jlmoney ?? 0) * 1);
      });

      this.goodsInfoArrGd.forEach((_g) => {
        allPrice += _g.ggnum * ((_g.price ?? 0) * 1 + (_g.jlmoney ?? 0) * 1);
      });

      console.log("allPrice", {
        allPrice,
        goodsInfoArrGd: this.goodsInfoArrGd,
        goodsInfoArr: this.goodsInfoArr,
      });

      return allPrice;
    },
    showGgCom: {
      get() {
        return this.value;
      },
      set(newVal) {
        this.$emit("input", newVal);
      },
    },
    xzSpecInfo() {
      if (this.goodsInfo.isSpecs == 1 && this.goodsInfo.specsData.length) {
        // console.log('xzSpecInfo', this.goodsInfo.specsData.find(v => v.a))
        return this.goodsInfo.specsData.find((v) => v.a);
      } else {
        return {};
      }
    },
    xzSxInfo() {
      let obj = {
        arr: [],
      };
      if (this.goodsInfo.isAttr == 1 && this.goodsInfo.attrData.length) {
        let r = this.goodsInfo.attrData,
          c = [];
        //把选中的属性找出来
        for (let n in r) {
          for (let d in r[n].attrStr) {
            if (r[n].attrStr[d].a) {
              c.push(r[n].attrStr[d]);
              break;
            }
          }
        }
        obj.arr = c;
      }
      return obj;
    },
    xzJlInfo() {
      let obj = {
        money: 0,
        arr: [],
      };
      if (
        this.goodsInfo.isMaterial == 1 &&
        this.goodsInfo.meterialData.length
      ) {
        let money = 0,
          arr = [];
        //把选中的加料加起来
        this.goodsInfo.meterialData.forEach((v) => {
          if (v.a) {
            obj.money += this.outin == 1 ? +v.SalesPrice : +v.SalesPrice;
            arr.push(v);
          }
        });
        obj.money = +obj.money.toFixed(2);
        obj.arr = arr;
      }
      return obj;
    },
  },
  watch: {
    async value(newVal) {
      if (newVal) {
        this.loading = true;
        this.goodsInfo = {};

        // 	goodsInfoArr: [], // 可选搭配的数据

        // goodsInfoArrGd: [], // 固定搭配的数组
        this.goodsInfoArr.splice(0, this.goodsInfoArr.length);
        this.goodsInfoArrGd.splice(0, this.goodsInfoArrGd.length);

        let { data } = await this.util.request({
          url: this.api.ggxq,
          // mask: 1,
          data: {
            id: this.co.id,
            storeId: this.storeid,
          },
        });

        const _obj = Object.assign(
          {},
          this.co,
          {
            ...data,
            kecomboGoodsArr: data?.kecomboGoodsArr?.map((_k, _index) => {
              return {
                ..._k,
                /* 可选搭配分组id */
                goodGroupId: _index,
                goods: _k.goods.map((_g) => {
                  return {
                    ..._g,
                    /* 固定搭配分组id */
                    goodGroupId: _index,
                  };
                }),
              };
            }),
          },
          {
            ggnum: 1,
          }
        );

        Object.keys(_obj).forEach((k) => {
          this.$set(this.goodsInfo, k, _obj[k]);
        });

        var that = this;
        // 初始化一个空数组来存储修改后的pv元素
        // 默认进来是 固定搭配
        if (this.goodsInfoArrGd.length === 0) {
          // 如果 goodsInfoArrGd 为空，则更新它
          this.goodsInfo.comboGoodsArr.forEach((pv) => {
            pv.jldata = "";
			
			
			// 默认
			var arr1 = pv['arrstr']
            pv.attribute = arr1;
			
            pv.ggnum = pv.num;
            pv.ggnumset = 2;

            this.goodsInfoArrGd.push(pv);
          });
        }
		
		// 可选搭配
        this.goodsInfoArr = [];
        this.loading = false;
        // console.log(this.goodsInfo)
      }
      // console.log('value', newVal)
    },
    // async co(newVal) {
    // 	// console.log('co', newVal, this.goodsInfo)
    // },
  },
};
</script>

<style scoped lang="scss">
.bs15 {
  border-radius: 30rpx 30rpx 0 0;
}

.f54 {
  font-size: 52rpx;
}

.ggjz {
  padding: 50rpx 50rpx 200rpx;
}

.jzi1 {
  height: 350rpx;
}

.jzi2 {
  margin-top: 50rpx;
}

.ggc {
  .ggx {
    padding: 20rpx 20rpx 40rpx 40rpx;
    opacity: 0.7;
  }

  .ggtop {
    padding: 40rpx 30rpx 0;
  }

  .ggh {
    width: 240rpx;
    height: 240rpx;
  }

  .ggb {
    max-height: calc(86vh - 233rpx - 280rpx);

    .specv {
      min-width: 185rpx;
      padding: 0 30rpx;
      height: 70rpx;
      border-radius: 8rpx;
      text-align: center;
      line-height: 70rpx;
      background: #f5f5f7;
      margin: 0 20rpx 20rpx 0;
    }
  }

  .ggf {
    box-shadow: 0 -2rpx 9rpx 2rpx rgba(221, 221, 221, 0.6);
    padding: 20rpx 36rpx;
    min-height: 153rpx;
  }

  .ggbtn {
    border-radius: 80rpx;
    height: 90rpx;
  }
}

@keyframes backOpacity {
  0% {
    opacity: 0.8;
  }

  50% {
    opacity: 0.6;
  }

  100% {
    opacity: 1;
  }
}

.dhtmd {
  animation: backOpacity 0.7s ease-in-out infinite;
}

.f-raw {
  flex-wrap: nowrap;
}

.jrgwctc {
  height: 30px;
  line-height: 30px;
  background-color: rgb(219, 168, 111);
  color: #fff;
  border-radius: 44px;
}
</style>